// 页面加载完成后执行
document.addEventListener('DOMContentLoaded', function () {
    // 加载科室选项
    loadDepartments();

    // 添加搜索输入事件监听
    const searchInput = document.getElementById('patient-search');
    searchInput.addEventListener('keydown', function (e) {
        if (e.key === 'Enter') {
            searchPatient();  // 按回车键时调用搜索病人
        }
    });

    // 添加表单提交事件监听
    const form = document.getElementById('case-form');
    if (form) {
        form.addEventListener('submit', function (e) {
            e.preventDefault();
            submitCase();
        });
    }
});

// 防抖函数
function debounce(func, wait) {
    let timeout;
    return function (...args) {
        clearTimeout(timeout);
        timeout = setTimeout(() => func.apply(this, args), wait);
    };
}

// 加载科室选项
function loadDepartments() {
    fetch('/api/departments')
        .then(response => response.json())
        .then(data => {
            if (data.msg === 'success') {
                const select = document.getElementById('dept-select');
                data.departments.forEach(dept => {
                    const option = document.createElement('option');
                    option.value = dept.dept_name;
                    option.textContent = dept.dept_name;
                    select.appendChild(option);
                });
            }
        })
        .catch(error => console.error('Error:', error));
}

// 搜索病人
function searchPatient() {
    const searchValue = document.getElementById('patient-search').value.trim();
    if (!searchValue) {
        hidePatientInfo();
        return;
    }

    fetch(`/api/patients/search?query=${encodeURIComponent(searchValue)}`)
        .then(response => response.json())
        .then(data => {
            if (data.msg === 'success' && data.patient) {
                showPatientInfo(data.patient);
                showCaseForm();
            } else {
                hidePatientInfo();
                showError('未找到病人信息');
            }
        })
        .catch(error => {
            console.error('Error:', error);
            showError('搜索病人时发生错误');
        });
}

// 显示病人信息
function showPatientInfo(patient) {
    const patientInfo = document.querySelector('.patient-info-section');
    patientInfo.style.display = 'block';

    document.getElementById('patient-id').textContent = patient.patient_id;
    document.getElementById('patient-name').textContent = patient.patient_name;
    document.getElementById('patient-gender').textContent = patient.gender;
    document.getElementById('patient-age').textContent = patient.age;
}

// 隐藏病人信息
function hidePatientInfo() {
    const patientInfo = document.querySelector('.patient-info-section');
    const caseForm = document.querySelector('.case-form-section');
    patientInfo.style.display = 'none';
    caseForm.style.display = 'none';
}

// 显示病例表单
function showCaseForm() {
    const caseForm = document.querySelector('.case-form-section');
    caseForm.style.display = 'block';
}

// 提交病例
function submitCase() {
    const patientId = document.getElementById('patient-id').textContent;
    const patientName = document.getElementById('patient-name').textContent;
    const deptName = document.getElementById('dept-select').value;
    const predictDays = document.getElementById('predict-days').value;
    const description = document.getElementById('description').value;

    // 验证必填字段
    if (!patientId || !patientName || !deptName || !predictDays || !description) {
        showError('请填写所有必要信息');
        return;
    }

    const caseData = {
        patient_id: patientId,
        patient_name: patientName,
        dept_name: deptName,
        predict_days: predictDays,
        description: description
    };

    fetch('/addCase', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify(caseData)
    })
        .then(response => response.json())
        .then(data => {
            if (data.msg === 'success') {
                showSuccess('病例创建成功');
                setTimeout(() => {
                    window.location.href = '/';  // 成功后跳转到首页
                }, 1500);
            } else {
                showError(data.error || '创建病例失败');
            }
        })
        .catch(error => {
            console.error('Error:', error);
            showError('提交病例时发生错误');
        });
}

// 重置表单
function resetForm() {
    document.getElementById('case-form').reset();
    document.getElementById('patient-search').value = '';
    hidePatientInfo();
}

// 显示错误信息
function showError(message) {
    const modal = document.getElementById('result-modal');
    const header = modal.querySelector('.modal-header h2');
    const body = modal.querySelector('.modal-body');

    header.textContent = '错误';
    header.style.color = '#dc3545';
    body.textContent = message;
    modal.style.display = 'block';
}

// 显示成功信息
function showSuccess(message) {
    const modal = document.getElementById('result-modal');
    const header = modal.querySelector('.modal-header h2');
    const body = modal.querySelector('.modal-body');

    header.textContent = '成功';
    header.style.color = '#28a745';
    body.textContent = message;
    modal.style.display = 'block';
}

// 关闭模态框
function closeModal() {
    const modal = document.getElementById('result-modal');
    modal.style.display = 'none';
}
